package com.solotiger.douban.ui.fragment;

import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.solotiger.douban.R;
import com.solotiger.douban.biz.event.BaseEvent;
import com.solotiger.douban.common.EventContants;
import com.solotiger.douban.util.RxBus;
import com.solotiger.douban.util.RxHelper;
import com.trello.rxlifecycle2.components.support.RxDialogFragment;

import io.reactivex.functions.Consumer;


public class LoadingViewFragment extends RxDialogFragment {

    public static final String TAG = LoadingViewFragment.class.getSimpleName();

    public static LoadingViewFragment newInstance() {
        return new LoadingViewFragment();
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        RxBus.INSTANCE.toObserverable()
                .compose(RxHelper.bind(this))
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) {
                        if (o instanceof BaseEvent) {
                            BaseEvent event = (BaseEvent) o;
                            if (event.getKey().equals(EventContants.FINISH_LOADING)) {
                                dismissAllowingStateLoss();
                            }
                        }
                    }
                });
        return inflater.inflate(R.layout.fragment_loading_view, container, false);
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        FragmentTransaction ft = manager.beginTransaction();
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
    }

    public void setCancel(boolean canCancel) {
        setCancelable(canCancel);
    }
}
